Shortest common supersequence¶
Time: O(MxN); Space: O(MxN); hard
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If multiple answers exist, you may return any of them.
(A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in the string S.)
Example 1:
Input: str1 = “abac”, str2 = “cab”
Output: “cabac”
Explanation:
str1 = “abac” is a subsequence of “cabac” because we can delete the first “c”.
str2 = “cab” is a subsequence of “cabac” because we can delete the last “ac”.
The answer provided is the shortest such string that satisfies these properties.
Constraints:
1 <= len(str1), len(str2) <= 1000
str1 and str2 consist of lowercase English letters.
Hints:
We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence.
1. Dynamic Programming [O(MxN), O(MxN)]¶
[1]:
class Solution1(object):
"""
Time: O(M*N)
Space: O(M*N)
"""
def shortestCommonSupersequence(self, str1, str2):
"""
:type str1: str
:type str2: str
:rtype: str
"""
dp = [[0 for _ in range(len(str2)+1)] for _ in range(2)]
bt = [[None for _ in range(len(str2)+1)] for _ in range(len(str1)+1)]
for i, c in enumerate(str1):
bt[i+1][0] = (i, 0, c)
for j, c in enumerate(str2):
bt[0][j+1] = (0, j, c)
for i in range(len(str1)):
for j in range(len(str2)):
if dp[i % 2][j+1] > dp[(i+1) % 2][j]:
dp[(i+1) % 2][j+1] = dp[i % 2][j+1]
bt[i+1][j+1] = (i, j+1, str1[i])
else:
dp[(i+1) % 2][j+1] = dp[(i+1) % 2][j]
bt[i+1][j+1] = (i+1, j, str2[j])
if str1[i] != str2[j]:
continue
if dp[i % 2][j]+1 > dp[(i+1) % 2][j+1]:
dp[(i+1) % 2][j+1] = dp[i % 2][j]+1
bt[i+1][j+1] = (i, j, str1[i])
i, j = len(str1), len(str2)
result = []
while i != 0 or j != 0:
i, j, c = bt[i][j]
result.append(c)
result.reverse()
return ''.join(result)
[3]:
s = Solution1()
str1 = "abac"
str2 = "cab"
assert s.shortestCommonSupersequence(str1, str2) == "cabac"